import Vue from 'vue'
import ls from 'store2'
import api from '@api';

export const inBrowser = typeof window !== 'undefined'

export const ua = () => {
  const userAgentInfo = inBrowser ? navigator.userAgent : ''
  const Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPod']
  let flag = 'PC'
  for (let vv = 0; vv < Agents.length; vv++) {
    if (userAgentInfo.indexOf(Agents[vv]) > 0) {
      flag = Agents[vv]
      break
    }
  }
  return flag
}

export const ssp = path => {
  if (!inBrowser) return
  const clientHeight = document.documentElement.clientHeight,
    scrollTop = ls.get(path)
  if (scrollTop) {
    Vue.nextTick().then(() => {
      if (document.body.clientHeight >= scrollTop + clientHeight) {
        window.scrollTo(0, scrollTop)
      }
      ls.remove(path)
    })
  }
}

export const strlen = str => {
  let charCode = -1
  const len = str.length
  let realLength = 0
  for (let i = 0; i < len; i++) {
    charCode = str.charCodeAt(i)
    if (charCode >= 0 && charCode <= 128) realLength += 1
    else realLength += 2
  }
  return realLength
}

export const cookie = function( name, value, days ){
  // if value is undefined, get the cookie value
  if( value === undefined ){
    var cookiestring = "; " + window.document.cookie;
    var cookies = cookiestring.split( "; " + name + "=" );
    if ( cookies.length === 2 ){
      return cookies.pop().split( ";" ).shift();
    }
    return null;
  }
  else {
    // if value is a false boolean, we'll treat that as a delete
    if( value === false ){
      days = -1;
    }
    var expires = "";
    if ( days ) {
      var date = new Date();
      date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
      expires = "; expires="+date.toGMTString();
    }
    window.document.cookie = name + "=" + value + expires + "; path=/";
  }
};

export const validate = {
  mobile(telephone) {
    let pattern = /^(1.[0-9]{9})$/;
    return pattern.test(telephone);
  },
  minLength(value, length) {
    return value.length >= length
  }
}

export const isWechat = function () {
  return /micromessenger/i.test(window.navigator.userAgent)
}

export const wechatConfig =   function (url) {
  if (!window.wx) {
    return
  }
  return new Promise(async function(resolve, reject) {
    let {data} = await api.get('api/v1/Wx/wxConfig.ashx', {url: url})
    if (data.StatusCode === '200') {
      let wx = window.wx
      wx.config({
        debug: false,
        appId: data.appId,
        timestamp: data.timestamp,
        nonceStr: data.nonceStr,
        signature: data.signature,
        jsApiList: [
          'onMenuShareTimeline',
          'onMenuShareAppMessage',
          'hideMenuItems',
          'chooseWXPay',
          'getLocation',
          'chooseImage',
          'uploadImage',
          'previewImage',
          'hideOptionMenu'
        ]
      })
    }
    wx.error(function(res){
      console.log(res)
    });
    resolve(data);
  })
}

export const timeCount = function (year, month, day) {
  let future = new Date(year, month-1, day), now = new Date();
  let dur = Math.round((future.getTime() - now.getTime()) / 1000) + future.getTimezoneOffset() * 60;
  let pms = {
    sec: "00",
    mini: "00",
    hour: "00",
    day: "00",
    month: "00",
    year: "0"
  };
  if(dur > 0){
    pms.sec = f.zero(dur % 60);
    pms.mini = Math.floor((dur / 60)) > 0? f.zero(Math.floor((dur / 60)) % 60) : "00";
    pms.hour = Math.floor((dur / 3600)) > 0? f.zero(Math.floor((dur / 3600)) % 24) : "00";
    pms.day = Math.floor((dur / 86400)) > 0? f.zero(Math.floor((dur / 86400)) % 30) : "00";
    pms.month = Math.floor((dur / 2629744)) > 0? f.zero(Math.floor((dur / 2629744)) % 12) : "00";
    pms.year = Math.floor((dur / 31556926)) > 0? Math.floor((dur / 31556926)) : "0";
  }
  return pms;
}
